package com.exam.stu.common.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.print.attribute.HashAttributeSet;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录过滤器
 * @author Administrator
 *
 */
public class LoginFilter implements Filter{

	public void destroy() {
		System.out.println("过滤器摧毁");
		
	}

	private static Set<String> whiteList ;
	
	static{
		whiteList = new HashSet<String>();
		whiteList.add("/login.do");
		whiteList.add("/404.do");
		whiteList.add("/dologin.do");
		whiteList.add("/logout.do"); 
		whiteList.add("/register.do"); 
		whiteList.add("/doregister.do"); 
	}
	
	
	
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpSession session = request.getSession(); 
		String uri = request.getRequestURI();
		
		String pre =  request.getContextPath() ;
		uri = uri.replace(pre, "");
		if (session.getAttribute("loginUser") == null && !whiteList.contains(uri)) {
			// 没有登录
			response.sendRedirect(request.getContextPath() + "/login.do");
		} else {
			// 已经登录，继续请求下一级资源（继续访问）
			arg2.doFilter(arg0, arg1);
		} 
//		arg2.doFilter(arg0, arg1);
	}

	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("过滤器初始化");
		
	}

}
